import {
    Component,
    Inject,
    OnInit
} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import 'rxjs/add/operator/map';
import { Router } from '@angular/router';

import { NzMessageService } from 'ng-zorro-antd';
import { UserService } from '../services/user.service';

import * as $ from 'jquery';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
    validateForm: FormGroup;
    fb: FormBuilder;
    message: NzMessageService;
    router: Router;
    userService: UserService;

    _submitForm() {
        for (const i in this.validateForm.controls) {
            if (i) {
                this.validateForm.controls[i].markAsDirty();
            }
        }
        if (this.validateForm.status !== 'VALID') {
            return;
        }
        this.userService
            .validateUser(
                this.validateForm.value.email,
                this.validateForm.value.password
            )
            .add(n => {
                if (this.userService.getUser() != null) {
                    this.router.navigate(['/content/home']);
                } else {
                    this.message.error('账户密码错误');
                }
            });
    }

    constructor(
        @Inject(FormBuilder) fb: FormBuilder,
        @Inject(NzMessageService) message: NzMessageService,
        @Inject(Router) router: Router,
        @Inject(UserService) userService: UserService
    ) {
        this.fb = fb;
        this.message = message;
        this.router = router;
        this.userService = userService;
    }

    ngOnInit() {
        this.validateForm = this.fb.group({
            email: [null, [Validators.required]],
            password: [null, [Validators.required]],
            remember: [true]
        });
    }
}
